package com.xxl.sso.server.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.sso.server.core.model.UserInfo;
import com.xxl.sso.server.core.result.ReturnT;
import com.xxl.sso.server.mapper.UserMapper;
import com.xxl.sso.server.service.UserService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserInfo> implements UserService {

//    private static List<UserInfo> mockUserList = new ArrayList<>();
//    static {
//        for (int i = 0; i <5; i++) {
//            UserInfo userInfo = new UserInfo();
//            userInfo.setUserid(1000+i);
//            userInfo.setUsername("user" + (i>0?String.valueOf(i):""));
//            userInfo.setPassword("123456");
//            mockUserList.add(userInfo);
//        }
//    }

    @Override
    public ReturnT<UserInfo> findUser(String username, String password) {

        if (username==null || username.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "Please input username.");
        }
        if (password==null || password.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "Please input password.");
        }

        // mock user
//        for (UserInfo mockUser: mockUserList) {
//            if (mockUser.getUsername().equals(username) && mockUser.getPassword().equals(password)) {
//                return new ReturnT<UserInfo>(mockUser);
//            }
//        }
        //根据用户名查询用户
        UserInfo userInfo = this.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUsername, username));
        if(!Objects.isNull(userInfo)) {
            //获取查询的用户名密码
            String userInfoPassword = userInfo.getPassword();
            //判断密码是否相等
            if(SecureUtil.md5(password).equals(userInfoPassword)) {
                return new ReturnT<UserInfo>(userInfo);
            }
        }
        return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "用户名或密码错误");

    }


}
